package com.example.onlinereadingsystem.demos.web.config.shiro.realm;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.onlinereadingsystem.demos.web.dto.domain.User;
import com.example.onlinereadingsystem.demos.web.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Description
 * @Author ljm
 * @Date 2024/10/9
 */
@Component
public class UserRealm extends AuthorizingRealm {
    @Autowired
    UserService userService;

    // 授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    // 认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        User user = new User();
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, token.getUsername());
        user = userService.getOne(queryWrapper);
        if (user.getPassword().equals(new String(token.getPassword()))) {
            return new SimpleAuthenticationInfo(user, user.getPassword(), user.getUsername());
        } else {
            System.out.println("用户名或密码错误！");
            throw new AuthenticationException("用户名或密码错误！");
        }
    }
}
